package com.meeting.meetingroom_api.specification;

import com.meeting.meetingroom_api.entity.Booking;
import com.meeting.meetingroom_api.entity.MeetingRoom;
import com.meeting.meetingroom_api.dto.MeetingRoomQueryDto;
import com.meeting.meetingroom_api.enums.BookingStatus; // Assuming you have this enum for Bookings
import com.meeting.meetingroom_api.enums.RoomStatus;
import jakarta.persistence.criteria.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class MeetingRoomSpecification {

    public static Specification<MeetingRoom> findByCriteria(MeetingRoomQueryDto queryDto) {
        return (Root<MeetingRoom> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 首先添加软删除过滤条件 - 确保不查询已删除的记录
            predicates.add(cb.equal(root.get("deleted"), false));

            if (StringUtils.hasText(queryDto.getName())) {
                predicates.add(cb.like(cb.lower(root.get("name")), "%" + queryDto.getName().toLowerCase() + "%"));
            }
            if (queryDto.getType() != null) {
                predicates.add(cb.equal(root.get("type"), queryDto.getType()));
            }
            if (queryDto.getMinCapacity() != null && queryDto.getMinCapacity() > 0) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("capacity"), queryDto.getMinCapacity()));
            }
            // 添加对5个设备字段的查询条件
            if (queryDto.getHasProjector() != null) {
                predicates.add(cb.equal(root.get("hasProjector"), queryDto.getHasProjector()));
            }

            if (queryDto.getHasSpeaker() != null) {
                predicates.add(cb.equal(root.get("hasSpeaker"), queryDto.getHasSpeaker()));
            }

            if (queryDto.getHasNetwork() != null) {
                predicates.add(cb.equal(root.get("hasNetwork"), queryDto.getHasNetwork()));
            }

            if (queryDto.getHasMicrophone() != null) {
                predicates.add(cb.equal(root.get("hasMicrophone"), queryDto.getHasMicrophone()));
            }

            if (queryDto.getHasWhiteboard() != null) {
                predicates.add(cb.equal(root.get("hasWhiteboard"), queryDto.getHasWhiteboard()));
            }

            if (queryDto.getStatus() != null) {
                predicates.add(cb.equal(root.get("status"), queryDto.getStatus()));
            }
            if (queryDto.getStatusList() != null && !queryDto.getStatusList().isEmpty()) {
                // 使用in查询代替单个equal
                predicates.add(root.get("status").in(queryDto.getStatusList()));
            }
            // 注释：时间段查询的状态计算逻辑在Service层进行，这里不处理

            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}